package com.wz.leetcode.string;

public class ConvertHex_405 {
    public static String toHex(int num) {
        if (num == 0) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 7; i >= 0; i--) {
            int value = (num >> (4 * i)) & 0xf;
            if (sb.length() > 0 || value > 0) {
                char digit = value < 10 ? (char)('0' + value) : (char)('a' + value - 10);
                sb.append(digit);
            }
        }
        return sb.toString();
    }

    public static String toHex1(int num) {
        if (num == 0) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < 8; k++) {
            int value = num & 0xf;
            char digit = value < 10 ? (char)('0' + value) : (char)('a' + value - 10);
            sb.append(digit);
            num = num >> 4;
        }
        return trimLeadingZeros(sb);
    }

    private static String trimLeadingZeros(StringBuilder sb) {
        int i = sb.length() - 1;
        while (i >= 0 && sb.charAt(i) == '0') {
            i--;
        }
        return new StringBuilder(sb.substring(0, i + 1)).reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(toHex(26));
        System.out.println(toHex(-1));

        System.out.println(toHex1(26));
        System.out.println(toHex1(-1));
    }
}
